import { reqGetInfo, reqGetUserDetailById, reqLogin } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    // token
    token: getToken() || '',
    // 个人资料
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    // 设置用户个人资料
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 移除Token
    delToken(state) {
      removeToken()
      state.token = ''
    },
    // 移除个人资料
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    //   token
    async login({ commit }, data) {
      const res = await reqLogin(data)
      commit('setToken', res.data)
    },
    // 用户资料
    async getUserInfo({ commit }) {
      const { data } = await reqGetInfo()
      const { data: data2 } = await reqGetUserDetailById(data.userId)
      const result = { ...data, ...data2 }
      commit('setUserInfo', result)
      return result
    },
    // 退出功能
    logout({ commit }) {
    //   提交删除 token 和 删除个人资料的 mutations
      commit('delToken')
      commit('delUserInfo')
    }
  },
  getters: {

  }
}
